<template>
  <div>
    <h5 class="text-center">
      <div>{{ related.customer_name }}</div>
      <div>解保审批表</div>
    </h5>

    <table class="table table-sm table-bordered approve-table" v-if="isCompany">
      <colgroup>
        <col width="20%" />
        <col width="30%" />
        <col width="20%" />
        <col width="30%" />
      </colgroup>
      <tbody>
        <tr>
          <td>客户名称</td>
          <td>{{ related.customer_name }}</td>
          <td>经营地址</td>
          <td>{{ related.address || '' }}</td>
        </tr>
        <tr>
          <td>组织类型</td>
          <td>{{ orgClassName }}</td>
          <td>统一信用代码</td>
          <td>{{ related.register_no || '' }}</td>
        </tr>
        <tr>
          <td>负责人名称</td>
          <td>{{ related.corp_name || '' }}</td>
          <td>联系电话</td>
          <td>{{ related.mobile_no || '' }}</td>
        </tr>
        <tr>
          <td>经营范围</td>
          <td colspan="3" class="text-left px-2">{{ related.business_scope || '' }}</td>
        </tr>
      </tbody>
    </table>

    <table class="table table-sm table-bordered approve-table" v-else>
      <colgroup>
        <col width="20%" />
        <col width="30%" />
        <col width="20%" />
        <col width="30%" />
      </colgroup>
      <tbody>
        <tr>
          <td>客户名称</td>
          <td>{{ related.customer_name }}</td>
          <td>联系电话</td>
          <td>{{ related.mobile_no || '' }}</td>
        </tr>
        <tr>
          <td>证件号</td>
          <td colspan="3">{{ related.lender_idcard || '' }}</td>
        </tr>
        <tr>
          <td>家庭地址</td>
          <td colspan="3">{{ related.address || '' }}</td>
        </tr>
        <tr>
          <td>经营范围</td>
          <td colspan="3" class="text-left text-indent">{{ related.business_scope || '' }}</td>
        </tr>
      </tbody>
    </table>

    <table class="table table-sm table-bordered approve-table">
      <colgroup>
        <col width="20%" />
        <col width="30%" />
        <col width="20%" />
        <col width="30%" />
      </colgroup>
      <tbody>
        <tr>
          <td>项目类型</td>
          <td>{{ guaTypeLabel }}</td>
          <td>担保产品</td>
          <td>{{ related.project_type_name || '' }}</td>
        </tr>
        <tr>
          <td>项目行业分类</td>
          <td>{{ related.ind_class_name }}</td>
          <td>贷款具体用途</td>
          <td>{{ related.use_category_name }}</td>
        </tr>
        <tr>
          <td>放款开始时间</td>
          <td>{{ $utils.dateFormat(related.load_date, 'yyyy-MM-dd') || '' }}</td>
          <td>放款结束时间</td>
          <td>{{ $utils.dateFormat(related.load_end_date, 'yyyy-MM-dd') || '' }}</td>
        </tr>
        <tr>
          <td>放款金额</td>
          <td>{{ related.reply_funds || '' }}万元</td>
          <td>在保余额</td>
          <td>{{ related.left_funds || '-' }} 万元</td>
        </tr>
        <tr class="bg-light">
          <td colspan="4" class="text-center py-2">解保信息</td>
        </tr>
        <template v-if="isView">
          <tr>
            <td>解保类型</td>
            <td>{{ enumUnGuaType[formData.un_gua_type] }}</td>
            <td>解保时间</td>
            <td>{{ $utils.dateFormat(formData.un_gua_time, 'yyyy-MM-dd') }}</td>
          </tr>
          <tr>
            <td>解保附件</td>
            <td colspan="3" class="px-3">
              <div v-for="file in areadyFiles" :key="file.url" class="d-flex">
                <attach-item :attach-data="file"></attach-item>
              </div>
            </td>
          </tr>
        </template>
        <template v-else>
          <tr>
            <td>
              <span class="text-danger">*</span>
              解保类型
            </td>
            <td class="report-input-td">
              <c-select
                v-model="formData.un_gua_type"
                class="w-100"
                placeholder="解保类型"
                :options="enumUnGuaType"
              ></c-select>
            </td>
            <td>
              <span class="text-danger">*</span>
              解保时间
            </td>
            <td class="report-input-td">
              <el-date-picker
                v-model="formData.un_gua_time"
                type="date"
                placeholder="解保时间"
                class="w-100"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </td>
          </tr>
          <tr>
            <td>解保附件</td>
            <td colspan="3" class="report-input-td text-left">
              <div class="d-flex align-items-stretch p-2">
                <div class="mr-3">
                  <input
                    type="file"
                    ref="uploadInput"
                    class="d-none"
                    multiple
                    accept="*"
                    @change="handleFileChange"
                  />
                  <el-button
                    plain
                    size="small"
                    class="mb-1"
                    icon="el-icon-upload2"
                    style="height: 100%"
                    :disabled="saveLoading"
                    @click="handleSelectFile"
                  >
                    上传
                  </el-button>
                </div>
                <div class="flex-1 bg-light p-2 rounded">
                  <div v-for="(file, i) in areadyFiles" :key="file.url" class="file-item">
                    <attach-item :attach-data="file"></attach-item>
                    <el-button type="text" :disabled="saveLoading" @click="handleDeleteFile(1, i)">
                      删除
                    </el-button>
                  </div>
                  <div v-for="(file, index) in uploadFiles" :key="index" class="file-item">
                    <attach-item :attach-data="file"></attach-item>
                    <el-button
                      type="text"
                      :disabled="saveLoading"
                      @click="handleDeleteFile(2, index)"
                    >
                      删除
                    </el-button>
                  </div>
                </div>
              </div>
            </td>
          </tr>
        </template>
      </tbody>
    </table>
    <div class="text-center my-3" v-if="!isView && !otherEdit">
      <el-button class="btn-long" type="primary" :loading="saveLoading" @click="submit">
        保存
      </el-button>

      <el-button class="btn-long" @click="beforClose">取消</el-button>
    </div>
  </div>
</template>

<script>
import { projectIsCompany } from '@/credit/views/county/unionProvince/components/projectApprove/index'
import { enumGuatype } from '@/bigcredit/views/ledger/reportMixins'
import { enumUnGuaType } from '@/bigcredit/views/loan/components/un/index'

import { fileAdapter, attachAdapter } from '@/bank/components/attach/index'
import { revokeObjectURL } from '@/common/plugins/tools/file'
import { uploadOss, deleteOss } from '@/common/api/oss'
import AttachItem from '@/bank/components/attach/Item'
import { arrayFromString, arrayToString } from '@vimi/utils-tool'

import { updateFlow, addFlow } from '@/bigcredit/views/loan/components/un/index'
import { mapGetters } from 'vuex'
export default {
  components: {
    AttachItem,
  },
  props: {
    relatedData: {
      type: Object,
      default: () => ({}),
    },
    unData: {
      type: Object,
      default: () => ({}),
    },
    viewMode: Boolean,
    otherEdit: Boolean,
  },
  data() {
    return {
      enumUnGuaType,
      saveLoading: false,
      related: {},
      formData: {
        un_gua_type: '',
        un_gua_time: '',
      },
      uploadFiles: [],
      areadyFiles: [],
      deleteFiles: [],
      tableName: 'un_gua_apply',
    }
  },
  computed: {
    ...mapGetters(['user']),
    enumOrgClass() {
      return this.$store.getters.enumOrgClassObj
    },
    guaType() {
      return +this.related.gua_type
    },
    guaTypeLabel() {
      return enumGuatype[this.guaType] || ''
    },
    isCompany() {
      return projectIsCompany(this.related)
    },
    orgClassName() {
      return this.enumOrgClass[this.related.org_class] || ''
    },
    isView() {
      return this.viewMode && !this.otherEdit
    },
    queryId() {
      return this.relatedData.customer_related_id
    },
    dataId() {
      return this.unData.un_gua_apply_id || ''
    },
  },
  watch: {
    relatedData: {
      handler: function (val) {
        this.related = val
      },
      immediate: true,
      deep: true,
    },
    unData: {
      handler: function (val) {
        Object.keys(this.formData).forEach(key => {
          this.formData[key] = val[key] || ''
        })

        this.areadyFiles = arrayFromString(val.un_gua_attachment).reduce((prev, curr) => {
          prev.push(
            attachAdapter({
              attachment: curr,
            })
          )
          return prev
        }, [])
      },
      immediate: true,
      deep: true,
    },
  },
  created() {
    this.$store.dispatch('getEnumOrgClass')
  },
  mounted() {},
  methods: {
    submit() {
      const msg = this.validate()
      if (msg) {
        this.$message.error(msg)
        return false
      }

      const promises = this.uploadFiles.map(it =>
        uploadOss({
          file: it.file,
          dir: `credit/unload/${this.queryId}`,
          type: 0,
          progress: ({ percent }) => {
            it.percent = percent
            it.loading = percent < 100
          },
        })
      )
      this.saveLoading = true
      return Promise.all(promises)
        .then(list => {
          const attachment = arrayToString([...this.areadyFiles.map(it => it.url), ...list])

          const data = {
            ...this.formData,
            customer_related_id: this.queryId,
            un_gua_attachment: attachment,
            un_gua_status: 1,
          }
          if (!this.otherEdit) {
            data.submit_person_name = this.user.realName
          }
          return this.dataId ? updateFlow(this.dataId, data) : addFlow(data)
        })
        .then(() => {
          if (!this.otherEdit) {
            this.$emit('success')
            this.$message.success('保存成功')
          }
        })
        .catch(err => {
          this.$message.error(err?.data?.error_description || '提交失败，请重试！')
        })
        .finally(() => {
          this.deleteOssFiles()
          this.saveLoading = false
        })
    },
    validate() {
      const validatePairs = {
        un_gua_type: '请选择解保类型',
        un_gua_time: '请填写解保日期',
      }
      for (const key in validatePairs) {
        if (!this.formData[key]) {
          return validatePairs[key]
        }
      }
      return ''
    },
    beforClose() {
      this.$emit('dismiss')
    },
    deleteOssFiles() {
      if (!this.deleteFiles.length) return
      deleteOss(this.deleteFiles.map(it => it.url))
    },
    handleDeleteFile(type, index) {
      if (type === 2) {
        const file = this.uploadFiles[index]
        revokeObjectURL(file.url)
        this.uploadFiles.splice(index, 1)
      } else {
        this.deleteFiles.push(...this.areadyFiles.splice(index, 1))
      }
    },
    handleSelectFile() {
      const { uploadInput } = this.$refs
      uploadInput.click()
    },
    handleFileChange(e) {
      const { files = [] } = e.target

      for (let i = 0; i < files.length; i++) {
        this.uploadFiles.push(fileAdapter(files[i]))
      }

      this.resetInput()
    },
    resetInput() {
      const { uploadInput } = this.$refs
      if (uploadInput) {
        uploadInput.value = ''
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.file-item {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px dotted #eee;

  &:last-child {
    border-bottom: none;
  }
}
.approve-table {
  text-align: center;
  margin-bottom: 0;
  margin-top: -1px;
  td {
    vertical-align: middle;
  }
}
</style>
